import { Component, OnInit,Input } from '@angular/core';
import { Router,ActivatedRoute } from '@angular/router';
//引用拦截器文件
import { InterceptorService } from "../../../../../share/interceptor.service";
import { ConfirmDialogModule, ConfirmationService,DialogModule,TabViewModule,DropdownModule} from 'primeng/primeng';
import { NoticeEntity } from '../../../../../models/notice-entity';
import { NzMessageService } from 'ng-zorro-antd';
import { forEach } from '@angular/router/src/utils/collection';
import { NoticeBrowseModel } from '../../../../../models/NoticeBrowseModel';
import { PeriodPersonModel } from '../../../../../models/PeriodPersonModel';
import { PersonalInfoEntity } from '../../../../../models/personal-info-entity';
import 'ztree';
import { timeInterval } from 'rxjs/operators/timeInterval';


@Component({
  selector: 'app-notice-detail',
  templateUrl: './notice-detail.component.html',
  styleUrls: ['./notice-detail.component.css']
})
export class NoticeDetailComponent implements OnInit {

  @Input() editNoticeDate: NoticeEntity=new NoticeEntity();  //保存根据category查询到的notice数据，全部的date
  // @Input() NoticeTreeDate：String[][] = new Array();  //保存根据查到的浏览人树形结构list
  @Input() NoticeTreeDate: string[] = new Array(); //保存根据查到的浏览人树形结构list
  @Input() noticeIDInfo: string;      //通知Id

  constructor(private router: Router,
    private confirmationService: ConfirmationService,
    private http: InterceptorService,
    private activeRoute:ActivatedRoute) { }

  
    id:any;
    ngOnInit() {
      this.id=this.activeRoute.snapshot.paramMap.get("id");
      this.getNotices();
      this.getCategory();
      // this.queryPage(this.noticeIDInfo);
      // this.getPerson();  //未根据通知id标记接受人的树形结构
      this.queryTreePage(); //根据通知id标记接受人的树形结构
    }

    ngOnChanges(){
      this.getNotices();

    }
  
    //获取通知信息
    getNotices() {
      // alert("是否进入getNotices方法"+this.editNoticeDate.columnId);
      this.noticeCategoryId=this.editNoticeDate.columnId;
      this.notifyInfo=this.editNoticeDate.noticeContent;
      this.notifyTitle=this.editNoticeDate.title;
      this.noticeCategory=this.editNoticeDate.columnName;    
    }
  
    noticeEntity: NoticeEntity=new NoticeEntity();//通知实体
    notices = new Array();
  
  
  
  //获取通知分类信息
  noticeCategory:any;  //通知类别
  noticeCategoryId:any; //选择的通知类型Id
  noticeCategoryNames:any[]=[];//通知类型选项
  noticeCategoryName:any;//通知类型选项
  notifyInfo:any;//通知内容
  notifyTitle:any;//通知标题
  
  //获取通知分类信息---显示
  getCategory(){
    let url="graduate-web/noticeCategory/selectNoticeCategoryInfo/";
    this.http.get(url).subscribe(res=>{
      if(res ==undefined){
        console.log("查询通知分类无返回结果")
      }else{
        if(res.json().code=='0000'){
          this.noticeCategoryNames = res.json().data;
          console.log(this.noticeCategoryNames)
        }else{
          console.log(res.json().message)
        }
      }
    })
  
  }
  
  zNodes:any[];
  setting = {
    data: {
      simpleData: {
        enable: true
      }
    },
    check: {
        enable: true
    }
  };
  personIds:any[]=[];
  periodPersonModels:PeriodPersonModel[]=[];
  //获取接收人信息
  getPerson(){
    let url = 'graduate-web/browse/findPeriodPersonModels/';
    this.http.get(url).subscribe(res=>{
      if(res ==undefined){
        console.log("查询接收人信息无返回结果")
      }else{
        if(res.json().code=='0000'){
          this.periodPersonModels=res.json().data;
          this.setPersonOptions();
        }else{
          console.log(res.json().message);
          this.showDialog(res.json().message+"\n请尝试刷新！");
        }
      }
    })
  }
  
  //设置人员树形结构
  setPersonOptions(){
    let nodes:any[]=[];
    nodes.push({id:0,name:'全部联系人'});
    this.periodPersonModels.forEach(periodPersonModel=>{
      nodes.push({id:periodPersonModel.periodId,pId:0,name:periodPersonModel.periodName});
      if(periodPersonModel.personalInfoList!=null){
        //接收人员信息
        let personalInfoEntitys:PersonalInfoEntity[]=periodPersonModel.personalInfoList;
        personalInfoEntitys.forEach(person=>{
          nodes.push({id:person.id,pId:periodPersonModel.periodId,name:person.name})
        })
      }
    })
    this.zNodes=nodes;
    //生成属性结构
    $.fn.zTree.init($("#ztree"),this.setting,this.zNodes);
  }
  
  
  
  
  //修改通知信
  editNotice(){
    // 验证数据内容
    //获取分类数据
    console.log(this.noticeCategoryId);
    if(this.noticeCategoryId ==undefined){
      console.log("请选择通知类别");
      this.showDialog("请选择通知类别");
      return;
    }
    this.noticeEntity.columnId=this.noticeCategoryId;
  
    //获取通知ID
    this.noticeEntity.id=this.noticeIDInfo;
    
    //获取接收人数据
    var treeObj =$.fn.zTree.getZTreeObj("ztree");
    var nodes = treeObj.getCheckedNodes();
    let browsePersons:NoticeBrowseModel[]=[];
    for(let i=0;i<nodes.length;i++){
      if (!nodes[i].isParent) {
        let browsePerson:NoticeBrowseModel=new NoticeBrowseModel();
        browsePerson.browsePersonId=nodes[i].id;
        browsePersons.push(browsePerson);
      } 
    }
    if(browsePersons.length==0){
      console.log("请选择接收人");
      this.showDialog("请选择接收人");
      return;
    }
    this.noticeEntity.browsePersons=browsePersons;
  
    //获取通知标题
    //获取通知内容
    if(this.notifyTitle==undefined){
      console.log("请输入通知标题");
      this.showDialog("请输入通知标题");
      return;
    }
    this.noticeEntity.title = this.notifyTitle;
  
    //获取通知内容
    if(this.notifyInfo==undefined){
      console.log("请输入通知内容");
      this.showDialog("请输入通知内容");
      return;
    }
    this.noticeEntity.noticeContent=this.notifyInfo;
  
    //补充其他数据
    this.noticeEntity.operator=localStorage.getItem('userName')==undefined?"大米时代":"大米时代";//操作人名称
    this.noticeEntity.operatorId=localStorage.getItem('userId')==undefined?"bjdmsd":this.noticeEntity.publisherId=localStorage.getItem('userId');//操作人Id
    this.noticeEntity.publisherId=localStorage.getItem('userId')==undefined?"bjdmsd":this.noticeEntity.publisherId=localStorage.getItem('userId');//创建人ID
    
    //提交到服务器
    let url="graduate-web/notice/updateNoticeBrowse/";
    // let url="graduate-web/notice/updateNotice/";
    let body=JSON.stringify(this.noticeEntity);
    this.http.post(url,body).subscribe(res=>{
      if(res ==undefined){
        console.log("查询通知分类无返回结果")
      }else {
        console.log(res.json().message);
        
        this.showDialog(res.json().message);
        //todo 如何延时触发跳转  
        if(res.json().code=='0000'){
          //返回上一页
          this.router.navigateByUrl("workspace/notice/my-notice/notice-all"); // 修改成功后跳转页面notice-all页面
          this.editNoticeFlag=false;   
          this.cancelNoticePageFlag=true; 
        }
      }
    })

    

  }
 
  //定义div是否显示标记
  editNoticeFlag=true;
  cancelNoticePageFlag=false;

  //取消修改
  cancelClick(){
    //清除数据
    this.personIds=[];
    this.noticeCategoryId=undefined;
    this.notifyInfo=undefined;
    this.router.navigateByUrl("workspace/notice/my-notice/notice-all");  //跳转到全部通知notice-all页面
    this.editNoticeFlag=false;   
    this.cancelNoticePageFlag=true;   //取消取消修改的路由跳转div
    
  }
  
  //**********************************************提示框Start**************************************88 */
  display:boolean=false;
  messages:"";
  /**
   * 提示框
   */
  showDialog(string){
    this.messages=string;
    this.display=true;
  }
  /**********************************************提示框END**************************************88 */
  
  
  
  /**填充页面资源树---全部接收人，并标记已选择的接收人
   * 
   */
  queryPage(id:String){
    //设置zTree属性
    let setting = {
      check: {
        enable: true,
        chkStyle: "checkbox",
        chkboxType: { "Y" : "ps", "N" : "ps" }
      },
      data: {
        simpleData: {
          enable: true,
          idKey: "id",
          pIdKey: "pId",
          rootPId: "0"
        }
      }
    };
    let nodes:any[]=[];
    nodes.push({id:0,name:'全部联系人'});
    $.fn.zTree.init($("#ztree"),setting,this.NoticeTreeDate);  //把父组件传过来的dataTree树填充到资源树中
  }
  
  /**条件查询-根据条件查询该人是否存在，并标记树形结构
   * 
   */
  SearchpersonName=this.SearchpersonName;  //获取搜索的姓名
  combinationSearch(id:String) {
    let url = "graduate-web/browse/selectBrowserByCombination/"+this.SearchpersonName+'/' +this.id ;  //后端联调
    //获取查询的姓名
    if(this.SearchpersonName==undefined){
      console.log("请输入查询的姓名");
      this.showDialog("请输入查询的姓名");
      return;
    }
  
    this.http.get(url).subscribe(
      res => {
        if (res.json().code == "0000") {
          if (res.json().message == "没有查询到此人") {
            console.log(res.json().message);
            this.showDialog("没有查询到此人!");
          } else {
            console.log("**************************重新加载树************************");
            //设置zTree属性
            let setting = {
              check: {
                enable: true,
                chkStyle: "checkbox",
                chkboxType: { "Y" : "ps", "N" : "ps" }
              },
              data: {
                simpleData: {
                  enable: true,
                  idKey: "id",
                  pIdKey: "pId",
                  rootPId: "0"
                }
              }
            };
            let zNodesData=res.json().data;
            let nodes:any[]=[];
            nodes.push({id:0,name:'全部联系人'});
            $.fn.zTree.init($("#ztree"),setting,zNodesData);
          }
        } 
      });
  }


/**填充页面资源树---全部接收人，并标记已选择的接收人
 * 
 */
queryTreePage(){
  //设置zTree属性
  let setting = {
    check: {
      enable: true,
      chkStyle: "checkbox",
      chkboxType: { "Y" : "ps", "N" : "ps" }
    },
    data: {
      simpleData: {
        enable: true,
        idKey: "id",
        pIdKey: "pId",
        rootPId: "0"
      }
    }
  };
  let zNodesData;
  // let selectTreeBrowserUrl:any;
  let url = "graduate-web/browse/selectAllBrowserByNoticeIdAsTree/"+this.noticeIDInfo;  //后端联调
  // let url =  'src/Data-Test/select-tree-browser.json' ;  //模拟数据
  this.http.get(url).subscribe(
    res =>{
      if(res.json().code == "0000"){
        zNodesData = res.json().data;
        let nodes:any[]=[];
        nodes.push({id:0,name:'全部联系人'});
        $.fn.zTree.init($("#ztree"),setting,zNodesData);
      }
    }
  )
}
}
